package souralven.jcomicreader.controller.reader.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import souralven.jcomicreader.controller.reader.FileReader;
import souralven.jcomicreader.util.ImageUtil;
import de.innosystec.unrar.Archive;
import de.innosystec.unrar.exception.RarException;
import de.innosystec.unrar.rarfile.FileHeader;

public class RarFileReader implements FileReader {

	@Override
	public InputStream read(final File file, final int imageNumber) {
		File temp = new File("/tmp");
		if (!temp.exists()) {
			temp.mkdir();
		}
		String tempDir = temp.getAbsolutePath();
		try {
			Archive a = new Archive(file);
			List<FileHeader> fileHeaders = a.getFileHeaders();
			Collections.sort(fileHeaders, new Comparator<FileHeader>() {
				@Override
				public int compare(FileHeader f1, FileHeader f2) {
					return f1.getFileNameString().compareTo(f2.getFileNameString());
				}
			});
			int count = 0;
            // TODO handle dirs
			for (FileHeader fileHeader : fileHeaders) {
			    if (ImageUtil.hasImageFormat(fileHeader.getFileNameString())) {
			        if (count == imageNumber) {
			            final File out = new File(tempDir + File.separator
			                + fileHeader.getFileNameString().trim());
			            final FileOutputStream os = new FileOutputStream(out);
			            a.extractFile(fileHeader, os);
			            os.close();
			            return new FileInputStream(out);
			        }
			        count++;
			    }
				fileHeader = a.nextFileHeader();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public int count(File file) {
		try {
			return new Archive(file).getFileHeaders().size();
		} catch (RarException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return 0;
	}
}
